//
//  PlayManager.m
//  MusicDemo
//
//  Created by lanou on 16/6/16.
//  Copyright © 2016年 lanou. All rights reserved.
//

#import "PlayManager.h"
@interface PlayManager()

@property (nonatomic,strong)AVPlayer *play;
@property (nonatomic,strong)NSTimer *timer;


@end

@implementation PlayManager
- (NSTimer *)timer{
    if (!_timer) {
        _timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(timeAction) userInfo:nil repeats:YES];//1.重复时间
    }
    return  _timer;
}


//属性单例；
- (AVPlayer *)play{
    if (!_play) {
        _play = [[AVPlayer alloc]init];
    }
    return _play;
}


//单例类创建
+ (instancetype)creatPlayManager{
    static PlayManager *a = nil;
    static dispatch_once_t oneceToKen;
    dispatch_once(&oneceToKen,^{
        a = [[PlayManager alloc]init];
    });
    return a;
}

//暂停
- (void)pauseMusic{
    [self.play pause];
    [self closeTimer];
    
    
}
//播放
- (void)playMusic{
    
    [self.play play];
    [self startTimer];
}

//准备去播放
- (void)prepareToPlayMusicWithUrl:(NSString *)url{
    //网址为空，不执行任何操作
    if (!url) {
        return;
    }
    //判断有没有播放的item
    if (self.play.currentItem) {
        //移除观察者
        [self.play.currentItem removeObserver:self forKeyPath:@"status"];
    }
    
    
    //创建一个item
    AVPlayerItem *item = [AVPlayerItem playerItemWithURL:[NSURL URLWithString:url]];
    //观察item的新值。其加载状态
    [item addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
    //替换当前item
    [self.play replaceCurrentItemWithPlayerItem:item];
    
    //播放完成后自动跳到下一首
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playMusicEnd) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
}



- (void)playMusicEnd{
    
    if ([self.delegate respondsToSelector:@selector(playToNextMusic)]) {
        [self.delegate playToNextMusic];
        [[NSNotificationCenter defaultCenter]removeObserver:self name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    }
}



//观察者事件
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
    //得到属性改变后的状态
    AVPlayerItemStatus status = [change[@"new"] integerValue];
    switch (status) {
        case AVPlayerItemStatusUnknown:
            NSLog(@"位置错误");
            break;
        case AVPlayerItemStatusReadyToPlay:
            //调用播放方法
            [self playMusic];
            NSLog(@"准备播放");
            break;
        case AVPlayerItemStatusFailed:
            NSLog(@"错误");
        
        default:
            break;
    }
}



//获取总时长
- (NSInteger)fetchTotalTime{
    //获取播放歌曲总时间
    CMTime time = self.play.currentItem.duration;
    //获取播放秒数 = time.value/time.timescale
    if (time.timescale == 0) {
        return 0;
    }
    return time.value/time.timescale;
}


//获取当前的播放的时间
- (NSInteger)fetchMusicCurrentTime{
    CMTime time = self.play.currentItem.currentTime;
    if (time.timescale == 0) {
        return 0;
    }
    return time.value/time.timescale;
}
//获取当前播放进度
- (CGFloat)fetchProgressValue{
    return [self fetchMusicCurrentTime]/(CGFloat)[self fetchTotalTime];
    
    
    
}
//将秒数转化00：00格式
- (NSString *)changeSecondsTime:(NSInteger)time {
    NSInteger min = time/60;
    NSInteger seconds = time%60;
    //时间格式，总是两位数
    return [NSString stringWithFormat:@"%.2ld:%.2ld",min,seconds];
}

//快进快退
- (void)playMusicWithSliderValue:(CGFloat)progress{
    //滑动之前先暂停音乐
    [self pauseMusic];
    [self.play seekToTime:CMTimeMake([self fetchTotalTime]*progress, 1) completionHandler:^(BOOL finished) {
        if (finished) {
            
            //完成以后继续播放
            [self playMusic];
        }
    }];
}


//定时器方法
- (void)timeAction{
    
    //NSLog(@"%ld",[self fetchMusicCurrentTime]) ;
    if ([self.delegate respondsToSelector:@selector(playManagerDelegateFetchTotalTime:currentTime:progress:)]) {
        
        
        [self.delegate playManagerDelegateFetchTotalTime:[self changeSecondsTime:[self fetchTotalTime]] currentTime:[self changeSecondsTime:[self fetchMusicCurrentTime]] progress:[self fetchProgressValue]];
    }
    
}
//开启定时器
- (void)startTimer{
    
    [self.timer fire];
}
//关闭定时器
- (void)closeTimer{
    
    [self.timer invalidate];
    //失效后置空
    self.timer = nil;
}

//是否正在播放
- (BOOL)isPlaying{
    
    if (self.play.rate==0) {
        return NO;
    }else{
        return YES;
    }
    
}



@end
